<?php 
//接受参数
$device_sn = $_GET['device_sn'];
$clientid = $_GET['clientid'];
//判断其中是否有参数是空值
if (!$device_sn || !$clientid) {
	$return_data['status'] = 1004;
	$return_data['content'] = '参数错误';
}else{
	$pdo = new PDO('mysql:host=localhost;dbname=device_binding','root','zqVnUy6cxsQXbpEZ');
	$pdo->exec('set names utf8');
	//分别查询设备号以及clientid是否已经存在
	$select_device_sql = "SELECT * FROM relation WHERE device_sn = '$device_sn' AND clientid = '$clientid'";
	$select_device_data = $pdo->query($select_device_sql)->fetch(PDO::FETCH_ASSOC);
	//判断查询结果只要有一个已经存在此条信息有误
	if (!empty($select_device_data)) {
		$return_data['status'] = 1003;
		$return_data['content'] = '参数已存在';
	}else{
		$sql = "SELECT * FROM relation WHERE device_sn = '$device_sn'";
		$data = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
		if ($data) {
			$delete_sql = "DELETE FROM relation WHERE device_sn = '$device_sn'";
			$pdo->exec($delete_sql);
		}
		//不存在，进行数据添加
		$insert_sql = "INSERT INTO relation(device_sn,clientid) VALUES('$device_sn','$clientid')";
		$res = $pdo->exec($insert_sql);
		if ($res) {
			//添加成功返回数据OK
			$return_data['status'] = 1001;
			$return_data['content'] = 'OK';
		}else{
			//添加失败返回数据NO
			$return_data['status'] = 1002;
			$return_data['content'] = 'NO';
		}
	}
}
//将数组装换为JSON格式输出返回
echo json_encode($return_data);
